#include <iostream>
#include <cerrno>
#include <string>
#include <jsoncpp/json/json.h>

#include "sock.hpp"
#include "protocol.hpp"

void usage(std::string proc)
{
  std::cout << "usage:\n\t" << proc << ": need server_ip server_port" << std::endl;
}

int main(int argc, char* argv[])
{
  if (argc != 3)
  {
    usage(argv[0]);
    return 1;
  }

  int sock = Sock::Socket();
  Sock::Connect(sock, argv[1], atoi(argv[2]));

  while(true)
  {
    //业务逻辑
    request_t req;
    memset(&req, 0, sizeof(req));
    std::cout << "please enter data left# ";
    std::cin >> req.left;
    std::cout << "please enter data right# ";
    std::cin >> req.right;
    std::cout << "please enter data operator# ";
    std::cin >> req.op;

    std::string json_string = serialize_request(req);
    write(sock, json_string.c_str(), json_string.size());

    char buffer[1024]; 
    ssize_t ret = read(sock, buffer, sizeof(buffer) - 1);
    if (ret > 0)
    {
        buffer[ret] = '\0';
        std::string str = buffer;

        response_t resp = deserialize_response(str);
    
        std::cout << "code : " << resp.code << std::endl;
        std::cout << "result : " << resp.result << std::endl;
        std::cout << std::endl;
    }
    else
    {
      perror("read");
      std::cout << "errno : " << errno << std::endl;
    }
  }

  return 0;
}
